package com.tutk.sample.AVAPI;


import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.IdRes;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xgakj.mylibrary.mvp.utils.ToastUtil;
import com.example.xgakj.newterminal.R;
import com.example.xgakj.newterminal.base.Parameters;
import com.example.xgakj.newterminal.utils.CaptureSreenUtil;
import com.socks.library.KLog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

//import com.xair.h264demo.R;

public class MainActivity2 extends AppCompatActivity {

    static String UID = "";
    static String UID_PASSWORD = "";
    @BindView(R.id.surfaceView1)
    SurfaceView surfaceView1;
    @BindView(R.id.rbt_silence)
    RadioButton rbtSilence;
    @BindView(R.id.rbt_listen)
    RadioButton rbtListen;
    @BindView(R.id.rbt_dialog)
    RadioButton rbtDialog;
    @BindView(R.id.rbt_group)
    RadioGroup rbtGroup;
    @BindView(R.id.btn_capture)
    TextView btnCapture;
    @BindView(R.id.btn_speak)
    TextView btnSpeak;
    @BindView(R.id.mainFrame)
    FrameLayout mainFrame;
    @BindView(R.id.cbx_recordVideo)
    CheckBox cbxRecordVideo;
    @BindView(R.id.rl_control)
    RelativeLayout rlControl;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Client.IOTC_ERRO:
                    ToastUtil.showShort(getApplicationContext(), "IOTC服务连接失败，请退出重连，多次失败请重启手机");
                    break;
                case Client.IOTC_SESSION_ERRO:
                    ToastUtil.showShort(getApplicationContext(), "IOTC通道连接失败，请退出重连");
                    break;
                case Client.AV_FAIL:
                    ToastUtil.showShort(getApplicationContext(), "UID登录失败，请退出重连，多次失败请检查UID设置");

                    break;
                case Client.AUDIO_Record_Failure:
                    ToastUtil.showShort(getApplicationContext(), "对讲通道连接失败，无法语音对讲");
                    break;
                default:
            }
            if (dialog != null) {
                dialog.dismiss();
            }
        }


    };


    private MediaCodec mCodec;

    // Video ConstantType
    private final static String MIME_TYPE = "video/avc"; // H.264 Advanced Video
    private final static int VIDEO_WIDTH = 608;
    private final static int VIDEO_HEIGHT = 448;
    ProgressDialog dialog;
    private int screenWidth;
    private int screenHeight;
    DisplayMetrics dm;
    ViewGroup.LayoutParams lp;
    private Client client;
    private boolean showControlLayout;
    private CaptureSreenUtil captureSreenUtil;


    /**
     * Called when the activity is first created.
     */

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);
        ButterKnife.bind(this);

        UID = getIntent().getStringExtra(Parameters.VIDEO_UID);
        UID_PASSWORD = getIntent().getStringExtra(Parameters.VIDEO_PASSWORD);

        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        lp = surfaceView1.getLayoutParams();
        if (isLandscape()) {
            screenWidth = dm.heightPixels;
            screenHeight = dm.widthPixels;
        } else {
            screenWidth = dm.widthPixels;
            screenHeight = dm.heightPixels;
        }
        dialog = new ProgressDialog(this);
        dialog.setMessage("正在连接服务器，请稍后");
        dialog.setCanceledOnTouchOutside(false);
        captureSreenUtil = new CaptureSreenUtil();
        captureSreenUtil.createEnvironment(MainActivity2.this);
        surfaceView1.getHolder().addCallback(new SurfaceHolder.Callback() {

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                // TODO Auto-generated method stub
                stopAV();
                KLog.d("shurun", "suface销毁");
            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                // TODO Auto-generated method stub
                KLog.d("shurun", "suface启动");
                if (mCodec == null) {
                    initDecoder();
                }

                dialog.show();
                client = new Client(UID,UID_PASSWORD,mHandler, mCodec);
                rbtGroup.check(R.id.rbt_silence);
                (new Thread() {
                    @Override
                    public void run() {
                        Log.i("shurun", "线程启动");

                        client.start();


                    }
                }).start();
                setSurfaceLayoutParameters();
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                // TODO Auto-generated method stub

            }
        });
        rbtGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.rbt_silence:
                        client.keepSilence();
                        break;
                    case R.id.rbt_dialog:
                        client.startTalk();
                        setAudioMode(MainActivity2.this, AudioManager.MODE_NORMAL);
                        break;
//                    case R.id.rbt_listen:
//                        client.keepSilence();
//                        client.startAudio();
//                        break;

                }
            }
        });

        /**
         * 从这里开始截屏
         */
        btnCapture.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onClick(View v) {
//                if (ClickUtil.isFastDoubleClick()) {
//                    return;
//                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (captureSreenUtil.startScreenCapture()) {
                        try {
                            Observable.create(new ObservableOnSubscribe<Boolean>() {
                                @Override
                                public void subscribe(@NonNull ObservableEmitter<Boolean> e) throws Exception {
                                    SystemClock.sleep(100);
                                    KLog.e("captureSreenUtil.startCapture();");
                                    captureSreenUtil.startCapture();
                                    e.onNext(true);
                                    e.onComplete();
                                }
                            })

                                    .subscribeOn(Schedulers.io())
                                    .doOnSubscribe(new Consumer<Disposable>() {
                                        @Override
                                        public void accept(@NonNull Disposable disposable) throws Exception {
                                            rlControl.setVisibility(View.INVISIBLE);
                                        }
                                    })
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(@NonNull Boolean aBoolean) throws Exception {
                                            ToastUtil.showShort(MainActivity2.this, "截图成功");
                                            KLog.e("截图成功不是第一次");
                                        }
                                    });

                        } catch (Exception e) {
                            ToastUtil.showShort(MainActivity2.this, "截图失败");
                            e.printStackTrace();
                        }
                    }
                } else {
                    ToastUtil.showShort(getApplicationContext(), "手机版本太低，无法截屏");
                }

            }
        });
        btnSpeak.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        client.stopAudio();
                        client.startRecord();

                        break;
                    case MotionEvent.ACTION_UP:
                        client.stoptRecord();
                        client.startAudio();
                        break;
                }
                return false;
            }

        });
        cbxRecordVideo.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    client.recodingVideo = true;
                } else {
                    client.recodingVideo = false;
                }
            }
        });

    }


    private void stopAV() {
        client.stopClient();
        SystemClock.sleep(100);
        stopDecoder();

    }


    public void initDecoder() {


        try {
            mCodec = MediaCodec.createDecoderByType(MIME_TYPE);
            MediaFormat mediaFormat = MediaFormat.createVideoFormat(MIME_TYPE,
                    VIDEO_WIDTH, VIDEO_HEIGHT);
            mCodec.configure(mediaFormat, surfaceView1.getHolder().getSurface(),
                    null, 0);
            mCodec.start();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("shurun", "解码器初始化异常");
            ToastUtil.showShort(this, "解码器初始化异常");
        }


        lp.width = screenWidth;
        float rate = (448 / (float) 608);
        Log.i("shurun2", rate + "");
        lp.height = (int) (screenWidth * rate);

        surfaceView1.setLayoutParams(lp);
//        setAudioMode(this, AudioManager.MODE_IN_COMMUNICATION);


    }

    public void stopDecoder() {
        if (mCodec != null) {
            mCodec.flush();

            mCodec.stop();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mCodec.reset();
            }

            mCodec.release();
            mCodec = null;
            Log.i("shurun", "mcodec释放");
        }
        setAudioMode(this, AudioManager.MODE_NORMAL);


    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onDestroy() {
        super.onDestroy();
        setAudioMode(this, AudioManager.MODE_NORMAL);
        if (captureSreenUtil!=null){
            captureSreenUtil.release();
            captureSreenUtil=null;
        }
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // TODO Auto-generated method stub
        super.onConfigurationChanged(newConfig);
        Log.i("pingmu", "++++++++++++*");
        setSurfaceLayoutParameters();

    }

    private void setSurfaceLayoutParameters() {
        KLog.e(screenWidth + "screenHeight:" + screenHeight);
        if (isLandscape()) {
            Log.i("pingmu", "横屏");


            lp.height = screenWidth;
            float rate = 608 / (float) 448;
            Log.i("shurun2", rate + "");
            lp.width = (int) (screenWidth * rate);


        } else {
            Log.i("pingmu", "shu屏");
            lp.width = screenWidth;
            lp.height = 448;
            float rate = 448 / (float) 608;
            Log.i("shurun2", rate + "");
            lp.height = (int) (screenWidth * rate);


        }
        surfaceView1.setLayoutParams(lp);
        KLog.e(lp.width + "surfaceView1Params:" + lp.height);
    }

    public boolean isLandscape() {
        Log.i("pingmu", "****");
        Configuration mConfiguration = this.getResources().getConfiguration(); // 获取设置的配置信息
        int ori = mConfiguration.orientation; // 获取屏幕方向

        if (ori == Configuration.ORIENTATION_LANDSCAPE) {

            // 横屏
            return true;
        } else if (ori == Configuration.ORIENTATION_PORTRAIT) {

            // 竖屏
            return false;
        }
        return false;
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CaptureSreenUtil.REQUEST_MEDIA_PROJECTION) {
            if (resultCode != Activity.RESULT_OK) {
                Toast.makeText(this, "User cancelled", Toast.LENGTH_SHORT).show();
                return;
            }
            if (this == null) {
                return;
            }
            captureSreenUtil.setmResultData(resultCode, data);
            KLog.e("onActivityResult 截图");
            try {
                Observable.create(new ObservableOnSubscribe<Boolean>() {
                    @Override
                    public void subscribe(@NonNull ObservableEmitter<Boolean> e) throws Exception {
                        SystemClock.sleep(1000);
                        captureSreenUtil.startCapture();
                        e.onNext(true);
                        e.onComplete();
                        KLog.e("subscribe 截图第一次");
                    }
                })

                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(@NonNull Disposable disposable) throws Exception {
                                KLog.e(Thread.currentThread().getName());
                                rlControl.setVisibility(View.INVISIBLE);
                            }
                        })
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(@NonNull Boolean aBoolean) throws Exception {
                                ToastUtil.showShort(MainActivity2.this,"截图成功");
                            }
                        });

            } catch (Exception e) {
                ToastUtil.showShort(MainActivity2.this,"截图失败");
                e.printStackTrace();
            }

        }

    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public void onPause() {
        super.onPause();
        captureSreenUtil.stopScreenCapture();
    }

    public void setAudioMode(Context ctx, int mode) {
        if (mode != AudioManager.MODE_NORMAL && mode != AudioManager.MODE_IN_COMMUNICATION) {
            return;
        }
        AudioManager audioManager = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
        if (mode == AudioManager.MODE_NORMAL) {
            audioManager.setSpeakerphoneOn(true);//打开扬声器
            KLog.d("yangshengqi", "开启");
        } else if (mode == AudioManager.MODE_IN_COMMUNICATION) {
            audioManager.setSpeakerphoneOn(true);//关闭扬声器
            KLog.d("yangshengqi", "开启");
        }
        audioManager.setMode(mode);
    }


    @OnClick(R.id.mainFrame)
    public void onViewClicked() {
        if (showControlLayout) {
            rlControl.setVisibility(View.VISIBLE);

        } else {
            rlControl.setVisibility(View.INVISIBLE);
        }
        showControlLayout = !showControlLayout;
    }
}



